package com.logindemo.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Base64;
import java.util.Date;
import java.util.UUID;

public class JwtUtil {
    //有效期
    private static final Long JWT_TTL = 60 * 60 * 1000L; //一小时后过期

    //密钥
    private static final String JWT_KEY = "sangeng";

    public static String getUuid(){
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 创建jwt构造
     * @param subject
     * @param ttlMillis
     * @param uuid
     * @return
     */
    private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid){
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        byte[] encodeKey = Base64.getDecoder().decode(JWT_KEY);
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        if(ttlMillis == null){
            ttlMillis = JWT_TTL;
        }
        long expMillis = nowMillis + ttlMillis;
        Date expDate = new Date(expMillis);
        return Jwts.builder()
                .setId(uuid)
                .setSubject(subject)
                .setIssuer("sg")
                .setIssuedAt(now)
                .signWith(signatureAlgorithm, encodeKey)
                .setExpiration(expDate);
    }

    /**
     * 生成Jwt令牌
     * @param subject
     * @param ttlMillis
     * @return
     */
    public static String createJwt(String subject, Long ttlMillis){
       return getJwtBuilder(subject,ttlMillis, getUuid()).compact();
    }

    public static String createJwt(String subject){
        return getJwtBuilder(subject, null, getUuid()).compact();
    }

    public static String createJwt(String subject, String uuid){
        return getJwtBuilder(subject, null, uuid).compact();
    }

    public static Claims parseJwt(String jwt){
        byte[] decode = Base64.getDecoder().decode(JWT_KEY);
        return Jwts.parser()
                .setSigningKey(decode)
                .parseClaimsJws(jwt)
                .getBody();
    }
}
